package com.gzz.controller;


import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gzz.common.DeviceInfo;
import com.gzz.common.R;
import com.gzz.pojo.Admin;
import com.gzz.pojo.OnlineUser;
import com.gzz.pojo.User;
import com.gzz.service.AdminService;
import com.gzz.utils.IPUtil;
import com.gzz.utils.JWTUtils;
import com.gzz.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.gzz.common.RedisUtils.User_Login_Key;
import static com.gzz.common.RedisUtils.User_Login_TTL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {
	@Autowired
	AdminService adminService;
	@Autowired
	StringRedisTemplate stringRedisTemplate;

	@PostMapping("/login")
	public R<String> adminLogin(HttpServletRequest httpServletRequest, @RequestBody Admin admin){
		String password = admin.getPassword();
		Digester md5 = new Digester(DigestAlgorithm.MD5);

		password = md5.digestHex(password);

		LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();

		lambdaQueryWrapper.eq(Admin::getAdminId,admin.getAdminId());

		Admin adm = adminService.getOne(lambdaQueryWrapper);

		if(adm == null){
			return R.error("用户名不存在!");
		}
		else{
			if(!adm.getStatus()){

				return R.error("账号已封禁");
			}
			String pw = adm.getPassword();
			if(!pw.equals(password)){
				return R.error("密码错误!");
			}
			else{
				//登录成功
				//1.保存用户信息到redis

				String token = JWTUtils.getToken(adm.getAdminId());
				//以token为key存入redis
				String tokenKey = User_Login_Key+adm.getAdminId().toString();

				stringRedisTemplate.opsForValue().set(tokenKey, token);
				stringRedisTemplate.expire(tokenKey,User_Login_TTL, TimeUnit.MINUTES);
				//3.将token返回到前端

				return R.success("登录成功").add("token",token);
			}
		}
	}
}

